/*
 * @Author: cl
 * @Description:
 * @Date: 2023-04-21 09:17:58
 * @LastEditTime: 2023-09-26 01:28:52
 * @FilePath: \jsnode\nestjs\naota\src\user\user.service.ts
 * @LastEditors: chenli 604089679@qq.com
 */
import { BadRequestException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import * as argon2 from 'argon2'
import { Repository } from 'typeorm'
import { CreateUserDto } from './dto/create-user.dto'
import { LoginUserDto } from './dto/login-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { User } from './entities/user.entity'
import { JwtService } from '@nestjs/jwt'
import { PrismaService } from '@/prisma/prisma.service'
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    private jwtService: JwtService,
    private prisma: PrismaService,
  ) {}

  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user'
  }

  async login(loginUserDto: LoginUserDto) {
    let user = await this.user.findOne({
      where: { name: loginUserDto.name },
    })

    if (!user) throw new BadRequestException('用户不存在!')
    const psMatch = await argon2.verify(user.password, loginUserDto.password)
    if (!psMatch) throw new BadRequestException('密码输入错误')
    const payload = { username: user.name, password: user.password }
    const token = this.jwtService.sign(payload)
    console.log(token)
    delete user.password
    return token
  }

  async register(loginUserDto: LoginUserDto) {
    if (!loginUserDto.name || !loginUserDto.password) {
      throw new BadRequestException('用户名密码不能为空!')
    }
    let user = await this.user.findOne({
      where: { name: loginUserDto.name },
    })
    if (user?.id) throw new BadRequestException('用户已存在!')
    let newUser = new User()
    newUser.name = loginUserDto.name
    newUser.password = await argon2.hash(loginUserDto.password)
    return this.user.save(newUser)
  }

  findAll() {
    return `This action returns all user`
  }

  findOne(id: number) {
    return `This action returns a #${id} user`
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`
  }

  remove(id: number) {
    return `This action removes a #${id} user`
  }
}
